import jwt
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
from .utils import CustomResponse


class TokenAuthMiddleware(MiddlewareMixin):
    """
    令牌认证中间件
    用于验证请求中的JWT令牌，确保API访问安全
    """

    def process_request(self, request):
        """
        处理每个进入的HTTP请求
        参数：
            request: HTTP请求对象
        返回：
            None: 验证通过
            Response: 验证失败时的错误响应
        """
        # 无需验证令牌的路径列表
        exempt_paths = [
            '/',  # 添加根路径
            '/api/auth/login',
            '/api/auth/register',
            '/api/auth/forgot-password',
            '/favicon.ico',
        ]

        # 对于豁免路径，直接放行
        if request.path in exempt_paths:
            return None

        # 获取请求头中的token
        token = request.headers.get('Authorization')
        if not token:
            return CustomResponse.error(msg="未提供token", status=401)

        try:
            # 验证token的有效性
            payload = jwt.decode(
                token.split(' ')[1],  # 移除'Bearer '前缀
                settings.SECRET_KEY,
                algorithms=['HS256']
            )
            # 将用户ID添加到请求对象中
            request.user_id = payload['user_id']
        except jwt.ExpiredSignatureError:
            return CustomResponse.error(msg="token已过期", status=401)
        except jwt.InvalidTokenError:
            return CustomResponse.error(msg="无效的token", status=401)

        return None